#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
调试选择器问题
"""

import logging
import time
from DrissionPage import Chromium

# 设置日志
logging.basicConfig(
    level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)


def debug_selector():
    """调试选择器问题"""
    try:
        logger.info("开始调试选择器问题...")

        # 创建浏览器实例
        browser = Chromium()
        tab = browser.latest_tab

        # 访问拉勾网
        url = "https://www.liepin.com/zhaopin/?inputFrom=c_index&workYearCode=0&key=AI%E5%89%8D%E7%AB%AF&scene=input&ckId=xju9kg19w73la3yv2t8wlxmyq9sq2eva&"
        logger.info(f"访问页面: {url}")

        tab.get(url)
        logger.info("等待页面加载...")
        time.sleep(5)  # 等待页面完全加载

        # 您的选择器
        card_selector = "#lp-search-job-box > div.content-wrap > section.content-left-section > div.job-list-box > div"

        logger.info(f"测试选择器: {card_selector}")

        # 方法1: 直接测试
        try:
            elements = tab.eles(card_selector)
            logger.info(f"方法1 - 直接测试: 找到 {len(elements)} 个元素")
        except Exception as e:
            logger.error(f"方法1失败: {e}")

        # 方法2: 逐步测试选择器的每个部分
        logger.info("\n=== 逐步测试选择器 ===")

        selectors_to_test = [
            "#lp-search-job-box",
            "#lp-search-job-box > div.content-wrap",
            "#lp-search-job-box > div.content-wrap > section.content-left-section",
            "#lp-search-job-box > div.content-wrap > section.content-left-section > div.job-list-box",
            "#lp-search-job-box > div.content-wrap > section.content-left-section > div.job-list-box > div",
        ]

        for selector in selectors_to_test:
            try:
                elements = tab.eles(selector)
                logger.info(f"'{selector}' - 找到 {len(elements)} 个元素")
                if len(elements) > 0:
                    # 显示第一个元素的类名
                    class_name = elements[0].attr("class")
                    logger.info(f"  第一个元素class: '{class_name}'")
            except Exception as e:
                logger.error(f"'{selector}' - 错误: {e}")

        # 方法3: 尝试简化的选择器
        logger.info("\n=== 尝试简化的选择器 ===")

        simple_selectors = [
            ".job-list-box",
            ".job-list-box > div",
            ".job-card-pc-container",
            ".job-item",
            "[class*='job-card']",
            "[class*='job-item']",
        ]

        for selector in simple_selectors:
            try:
                elements = tab.eles(selector)
                logger.info(f"'{selector}' - 找到 {len(elements)} 个元素")
            except Exception as e:
                logger.error(f"'{selector}' - 错误: {e}")

        # 方法4: 检查页面是否完全加载
        logger.info("\n=== 检查页面状态 ===")
        logger.info(f"当前URL: {tab.url}")
        logger.info(f"页面标题: {tab.title}")

        # 等待更长时间再试
        logger.info("等待10秒后重试...")
        time.sleep(10)

        try:
            elements = tab.eles(card_selector)
            logger.info(f"等待后重试: 找到 {len(elements)} 个元素")
        except Exception as e:
            logger.error(f"等待后重试失败: {e}")

        # 方法5: 使用XPath
        logger.info("\n=== 尝试XPath选择器 ===")
        xpath_selectors = [
            "//*[@id='lp-search-job-box']//div[@class='job-list-box']/div",
            "//div[@class='job-list-box']/div",
            "//div[contains(@class, 'job-card')]",
            "//div[contains(@class, 'job-item')]",
        ]

        for xpath in xpath_selectors:
            try:
                elements = tab.eles(xpath)
                logger.info(f"XPath '{xpath}' - 找到 {len(elements)} 个元素")
            except Exception as e:
                logger.error(f"XPath '{xpath}' - 错误: {e}")

        logger.info("调试完成！")

    except Exception as e:
        logger.error(f"调试过程中出错: {e}")
        raise
    finally:
        # 关闭浏览器
        try:
            browser.quit()
        except:
            pass


if __name__ == "__main__":
    debug_selector()
